package com.ym521.mykotlinext

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.ym521.mykotlinext.databinding.MessageItemBinding

/**
 *@author Ym
 *E-mail: 2435970206@qq.com
 *createTime:2024/4/5
 *explain:
 *
 */
class MessageAdapter : RecyclerView.Adapter<ViewHolder>() {

    private val dataList = arrayListOf<String>()

    fun addMessage(string: String) {
        val index = dataList.size
        dataList.add(string)
        notifyItemInserted(index)
    }

    fun count(): Int = dataList.size


    fun lastIndex(): Int = count() - 1


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val viewBind =
            MessageItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MessageViewHolder(viewBind)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (holder is MessageViewHolder)
            holder.showData(dataList[position])
    }

    private class MessageViewHolder(val viewBind: MessageItemBinding) : ViewHolder(viewBind.root) {

        fun showData(msg: String) {
            viewBind.tvMessage.text = msg
        }
    }
}